<template>
  <div class="transition-router" :class="{'router-in-transition': transition}">
    <transition
      :name="transitionName"
      @beforeEnter="beforeEnter"
      @after-enter="afterEnter"
      @enter-cancelled="enterCancelled"
      @beforeLeave="beforeLeave"
      @after-leave="afterLeave"
      @leave-cancelled="leaveCancelled">
      <slot></slot>
    </transition>
  </div>
</template>

<script>
  // 路由组件动画切换效果组件
  const HISTORIES_KEY = '__HISTORIES_KEY__'
  const histories = (sessionStorage.getItem(HISTORIES_KEY) || '').split(',').filter(Boolean)

  let lastLocation = { isPush: true }
  const isHistoryPush = (router) => {
    // (history.state && history.state.key)
    const key = router.name
    if (key !== lastLocation.key) {
      const index = histories.lastIndexOf(key)

      if (index > -1) {
        histories.splice(index + 1)
      } else {
        histories.push(key)
      }

      sessionStorage.setItem(HISTORIES_KEY, histories.join(','))

      lastLocation = {
        isPush: index < 0,
        key
      }
    }
    return lastLocation.isPush
  }
  export default {
    name: 'animated-router',
    data() {
      return {
        transition: false,
        // 路由前进name: forward
        // 路由后退name: backward
        // 路由淡入淡出: faded
        transitionName: 'faded'
      }
    },
    methods: {
      setTransition(boo) {
        this.transition = boo
      },
      beforeEnter(el) {
        this.setTransition(true)
      },
      afterEnter(el) {
        this.setTransition(false)
      },
      enterCancelled(el) {
        this.setTransition(false)
      },
      beforeLeave(el) {
        this.setTransition(true)
      },
      afterLeave(el) {
        this.setTransition(false)
      },
      leaveCancelled(el) {
        this.setTransition(false)
      }
    },
    created() {
      // $route的变化前提是history.state.key已经发生了变化，所以这里用history.state.key来记录历史
      this.$watch('$route', (n, o) => {
        const isForward = isHistoryPush(n)
        // 不应用左右滑动切换效果的路由
        const fadeRouteName = ['home', 'corpHome', 'service', 'news', 'user', 'corp']
        if ((fadeRouteName.indexOf(n.name) !== -1 && fadeRouteName.indexOf(o.name) !== -1) || !o.name) {
          this.transitionName = 'faded'
        } else {
          this.transitionName = isForward ? 'forward' : 'backward'
        }
      })
    }
  }
</script>

<style lang="scss">
  @import "../../common/style/animated-router";
</style>
